import os
import os.path
import sys
import copy
import mdf.debug
import mdf.config
import mdf.utils

from jinja2 import Environment, PackageLoader, Template, FileSystemLoader, evalcontextfilter, Markup, escape
loader = FileSystemLoader( mdf.config.default_template_dir )
env = Environment( loader = loader )
env.filters['nl2br'] = mdf.utils.nl2br

class RSS:
	def __init__( self, outputfile ):
		self.outputfile = outputfile
		mdf.debug.dprint( outputfile )
		self.title = None
		self.link = None
		self.pubdate = None
		self.description = None
		self.articles = []
	
	def add_packages( self, packages ):
		for p in packages:
			self.articles.append( p.writeup )
		self.articles = sorted( self.articles, key = lambda article: article.date )
		if len(self.articles) > 10:
			self.articles = self.articles[:10]
		for i in xrange( 0, len(self.articles) ):
			self.articles[i].article = mdf.utils.to_html_entity( self.articles[i].article.replace("[NL2BR]","") )
	
	def render( self, packages ):
		#select last 10 posts
		last10 = []
		for pkg in packages:
			last10.append( pkg.writeup )
		last10 = sorted( last10, key = lambda article: article.date_extended )
		last10 = copy.deepcopy( last10[len(last10)-10:] )
		#last5 = reversed( last5 )
		last10.reverse()
		#for i in range(0,len(last10)):
		#	last10[i].article = last10[i].article[:100]
		for a in last10:
			a.article = mdf.utils.to_html_entity( a.article.replace("[NL2BR]","") )
		templ = env.get_template( "rss.thtml" )
		f = open( self.outputfile , "w" )
		f.write( templ.render( rss = last10 ) )
		f.close()




